// React 版本的 ROS2 Web控制台（核心功能与结构迁移）
// 文件: RosWebConsole.tsx

import React, { useEffect, useRef, useState } from 'react';
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Row,
  Select,
  Slider,
  Space,
  Typography,
  message,
} from 'antd';

const { TextArea } = Input;
const { Title } = Typography;

const lightPresets = {
  forward: { x: 1, y: 0, z: 0, yaw: 0 },
  backward: { x: -1, y: 0, z: 0, yaw: 0 },
  left: { x: 0, y: 0, z: 0, yaw: 1 },
  right: { x: 0, y: 0, z: 0, yaw: -1 },
  left_shift: { x: 0, y: 1, z: 0, yaw: 0 },
  rught_shift: { x: 0, y: -1, z: 0, yaw: 0 },
};

const RosWebConsole: React.FC = () => {
  const [server, setServer] = useState('ws://192.168.0.140:8001/ws');
  const [socket, setSocket] = useState<WebSocket | null>(null);
  const [status, setStatus] = useState<'connected' | 'connecting' | 'disconnected'>('disconnected');
  const [log, setLog] = useState<string[]>([]);
  const [commandJson, setCommandJson] = useState(JSON.stringify(lightPresets.red_breathing, null, 2));
  const [customTopic, setCustomTopic] = useState('api/sport/request');
  const [mode, setMode] = useState(1);
  const [rgb, setRgb] = useState({ r: 255, g: 0, b: 0 });
  const logRef = useRef<HTMLDivElement>(null);

  const logMessage = (msg: string) => {
    setLog(prev => [...prev.slice(-49), `[${new Date().toLocaleTimeString()}] ${msg}`]);
  };

  const connect = () => {
    if (socket) socket.close();
    logMessage('连接中...');
    setStatus('connecting');

    const ws = new WebSocket(server);

    ws.onopen = () => {
      logMessage('✅ 已连接 ROS WebSocket');
      setStatus('connected');
    };
    ws.onerror = err => {
      logMessage('❌ WebSocket 错误');
      setStatus('disconnected');
    };
    ws.onclose = () => {
      logMessage('⚠️ 已断开连接');
      setStatus('disconnected');
    };

     // ✅ 添加这段监听消息的处理逻辑
    ws.onmessage = (event) => {
      try {
        const msg = JSON.parse(event.data);
        logMessage(`📩 收到ROS返回: ${JSON.stringify(msg, null, 2)}`);
      } catch (err) {
        logMessage(`⚠️ 无法解析ROS返回: ${event.data}`);
      }
    };
    setSocket(ws);
  };

  const disconnect = () => {
    socket?.close();
    setSocket(null);
  };

  const sendCommand = () => {
    if (!socket || socket.readyState !== WebSocket.OPEN) return message.error('未连接 WebSocket');
    try {
      const data = JSON.parse(commandJson);
      const msg = { topic: '/' + customTopic, data }; 
      socket.send(JSON.stringify(msg));
      logMessage(`已发送指令: ${JSON.stringify(msg)}`);
    } catch (err) {
      message.error('JSON格式错误');
    }
  };

  const applyPreset = (presetKey: keyof typeof lightPresets) => {
    const preset = lightPresets[presetKey];
    setMode(preset.mode);
    setRgb({ r: preset.r, g: preset.g, b: preset.b });
    setCommandJson(JSON.stringify(preset, null, 2));
    sendCommand();
  };

  useEffect(() => {
    const jsonData = { mode, ...rgb };
    setCommandJson(JSON.stringify(jsonData, null, 2));
  }, [mode, rgb]);

  useEffect(() => {
    logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: 'smooth' });
  }, [log]);

  return (
    <div className="container" style={{ padding: 24 }}>
      <Title level={2}>ROS2 Web控制台</Title>
      <Space align="center" style={{ marginBottom: 16 }}>
        <span>连接状态：</span>
        <span style={{ color: status === 'connected' ? 'green' : status === 'connecting' ? 'orange' : 'red' }}>{status}</span>
      </Space>
      <Row gutter={16}>
        <Col span={8}>
          <Card title="连接管理">
            <Form layout="vertical">
              <Form.Item label="服务器地址">
                <Input value={server} onChange={e => setServer(e.target.value)} />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" onClick={connect}>连接</Button>
                  <Button danger onClick={disconnect}>断开</Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
          <Card title="灯光预设" style={{ marginTop: 24 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              {Object.entries(lightPresets).map(([key, val]) => (
                <Button key={key} block onClick={() => applyPreset(key as any)}>
                  {key}
                </Button>
              ))}
            </Space>
          </Card>
        </Col>
        <Col span={16}>
          <Card title="自定义 JSON 命令">
            <Row gutter={16}>
              <Col span={12}>
                <Form layout="vertical">
                  <Form.Item label="目标主题">
                    <Input value={customTopic} onChange={e => setCustomTopic(e.target.value)} prefix="/" />
                  </Form.Item>
                  <Form.Item label="灯光模式">
                    <Select value={mode} onChange={setMode} options={[
                      { label: '常亮', value: 0 },
                      { label: '呼吸', value: 1 },
                      { label: '闪烁', value: 2 },
                    ]} />
                  </Form.Item>
                  <Form.Item label="RGB设置">
                    <Row gutter={8}>
                      {(['r', 'g', 'b'] as const).map(c => (
                        <Col span={8} key={c}>
                          <label>{c.toUpperCase()}</label>
                          <Slider
                            min={0}
                            max={255}
                            value={rgb[c]}
                            onChange={v => setRgb(prev => ({ ...prev, [c]: v }))}
                          />
                        </Col>
                      ))}
                    </Row>
                  </Form.Item>
                </Form>
              </Col>
              <Col span={12}>
                <TextArea rows={10} value={commandJson} onChange={e => setCommandJson(e.target.value)} />
              </Col>
            </Row>
            <Button type="primary" style={{ marginTop: 16 }} onClick={sendCommand}>发送 JSON 命令</Button>
          </Card>
        </Col>
      </Row>
      <Card title="系统日志" style={{ marginTop: 24 }}>
        <div ref={logRef} style={{ maxHeight: 240, overflowY: 'auto', fontFamily: 'monospace' }}>
          {log.map((line, i) => <div key={i}>{line}</div>)}
        </div>
      </Card>
    </div>
  );
};

export default RosWebConsole;
